#!/usr/bin/env python
# encoding=utf-8
import json
import re
import sys

from fuzzywuzzy import fuzz
from pymongo import MongoClient
from scpy.logger import get_logger
from scpy.xawesome_location import parse_location
from xtls.codehelper import timeit

from config import *
from util import query_location

reload(sys)
sys.setdefaultencoding('utf-8')

__author__ = 'xlzd'
logger = get_logger(__file__)
MONGO = MongoClient(MONGO_HOST, MONGO_PORT)
MG_BUILDING_CONN = MONGO[DB_NAME]['officeBuilding']
MG_ITEMS_CONN = MONGO[DB_NAME]['officeItems']
PATTERN_ADDRESS_TAIL = re.compile(ur'附[\d零〇一二三四五六七八九十百]+号.+')


def match_loaction(company_name, address):
    raw_address = address
    location = parse_location(address)
    if not location:
        raise RuntimeError('address not found : %s' % address)
    if location['cityName'] in address:
        address_split = address.split(location['cityName'])[-1]
    elif location['cityShortName'] in address:
        address_split = address.split(location['cityShortName'])[-1]
    else:
        address_split = address
    address = PATTERN_ADDRESS_TAIL.sub('', address_split)

    locations = query_location(location['cityName'], address)
    if not locations:
        locations = query_location(location['cityName'], address_split)

    nowmax_score, nowmax_place = -1, None
    for place in locations:
        print json.dumps(place, ensure_ascii=False, indent=4)
        score = 0
        if address in place['address'] or place['address'] in raw_address:
            score += 1
        else:
            score += (fuzz.ratio(address, place['address']) / 100.)

        tag = place.get('detail_info', {'tag': ''}).get('tag', '')
        if u'写字楼' in tag or u'公司' in tag or u'企业' in tag:
            score += 0.5
        elif u'房地产' in tag:
            score += 0.3

        if company_name in place['name'] or place['name'] in company_name:
            score += 1
        else:
            score += (fuzz.ratio(company_name, place['name']) / 100.)

        if nowmax_score < score:
            nowmax_score = score
            nowmax_place = place
    print json.dumps(nowmax_place, ensure_ascii=False, indent=4, sort_keys=True)
    print nowmax_score
    return nowmax_place['location']['lat'], nowmax_place['location']['lng']


@timeit
def main(company_name, address):
    lat, lng = match_loaction(company_name, address)
    print lat, lng
    # buildings = MG_BUILDING_CONN.find({'coordinate': {'$near': [lat, lng]}}).limit(5)
    buildings = MG_BUILDING_CONN.find(
        {'coordinate': {'$geoWithin': {'$center': [[lat, lng], 0.013]}}}
    ).limit(10)

    total_sample = total_price = total_building = 0
    for index, item in enumerate(buildings, start=1):
        if item['sampleCount'] == 0 or item['averagePrice'] == 0:
            continue
        total_price += item['averagePrice']
        total_sample += item['sampleCount']
        total_building += 1
        del item['updateTime']
        print index, json.dumps(item, ensure_ascii=False, indent=4, sort_keys=True)

    unit_price = total_price / total_building

    print total_price, total_sample, total_building
    print unit_price, total_sample

    data = {
        'companyName': company_name,
        'companyAddress': address,
        'unitPrice': unit_price,
        'officeSample': total_sample,
        'buildingSample': total_building,
    }
    print json.dumps(data, ensure_ascii=False, indent=4, sort_keys=True)

    # print json.dumps(query_location(city=u'重庆', address=u'沙坪坝区富洲路12号'), ensure_ascii=False, indent=4, sort_keys=True)
    # db.collection.find( {field: {$near: [1, 2], $maxDistance: 10}} )
    # db.collection.find( {field: {$geoWithin: {$center: [[经,纬,] 半径]}}} )
#
#
# 纬度1度： 110.94km
# 经度1度： 96.3km


if __name__ == '__main__':
    main(u'重庆速展文化传播有限公司', u'重庆市沙坪坝区富洲路12号附7号8-4')
